define(function (require) {
    'use strict';

    var  distpicker = require ('common/distpicker.min'), xdate = require('xdate');

    function ctrl($scope,$state,$ionicLoading,$ionicModal,$q,$ionicPopup,CommonService,DictionaryService,WebService,LocalCacheService) {

        var par = $scope.param = {};
        par.profession_ads = DictionaryService.getProfessionAds();
        par.degree_ads =  DictionaryService.getDegreeAds();
        par.address = {};
        par.user = {};
        par.profession_code = "04";
        par.degree_code = "4";


        $scope.$on('$ionicView.beforeEnter', function() {
            init();
        });

        function init(){
            //获取开户用户
            WebService.getCurrentOpenUser().then(
                function (data){
                    par.client_name = data.client_name;
                    par.id_no = data.id_no;
                    par.branch_no = data.branch_no;
                    par.issued_depart = data.issued_depart;
                    par.id_address = data.address;
                    par.id_begindate = CommonService.stringToDate(data.id_begindate);
                    var id_enddate = DictionaryService.getEndtime(data.id_enddate);
                    if(id_enddate == DictionaryService.getDefEndtime()){
                        par.isLongTerm = true;
                    }
                    par.id_enddate = CommonService.stringToDate(id_enddate);

                }, function(){
                    $state.go("open-msgVerify");
                }
            );

            createModel();
        }

        function createModel(){
            var deferred = $q.defer();
            if(!$scope.address_modal) {
                $ionicModal.fromTemplateUrl("open/changeAddress.html", {
                    scope: $scope,
                    animation: "slide-in-up"
                }).then(function(modal) {
                    $scope.address_modal = modal;
                    deferred.resolve();
                });
            } else {
                deferred.resolve();
            }
            return deferred.promise;
        }


        $scope.showIdNoInfo = function(){
            var myPopup = $ionicPopup.show({
                cssClass: "kDialog",
                template: "为保证身份证号与您上传的身份证上一致，身份证号不允许修改。<br/>" +
                    "如身份证号有误，请选择”返回重传“，返回上一步重传身份证正面照片，务必保证扫描出正确的身份证号。<br/><br/>" +
                    "<p class='fs0'>如有疑问，请联系客服：400-800-5000。</p>",
                scope: $scope,
                buttons: [
                    { text: "<b>取消</b>" },
                    { text: "返回重传",
                        type: "button-positive",
                        onTap: function(e) {
                            $scope.goUploadId();
                            return false;
                        }
                    },
                ]
            });
        }

        $scope.goUploadId = function(){
            $state.go("open-uploadID");
        }


        $scope.goChangeAddress = function(){
            $scope.address_modal.show();
            $("#distpicker").distpicker({ autoSelect: false});
        }

        $scope.changeAddress = function(){
            if(!par.address.province){
                CommonService.showAlert({message:"请选择省！"});
                return;
            }
            if(!par.address.city){
                CommonService.showAlert({message:"请选择市！"});
                return;
            }
            var cityElement = angular.element(document.querySelector('#city'));
            var cityCode = null;
            if(cityElement.find("option:selected") == 0) {
                cityCode = $("#city option:last").attr("data-code");
            } else {
                cityCode = $("#city option:selected").attr("data-code");
            }
            var districts = ChineseDistricts[cityCode];
            if(!par.address.district && districts){
                CommonService.showAlert({message:"请选择区！"});
                return;
            }
            if(!par.address.more){
                CommonService.showAlert({message:"请输入详细门牌信息！"});
                return;
            }
            par.id_address = par.address.province + par.address.city + par.address.district + par.address.more;
            $scope.address_modal.hide();

        }

        $scope.closeModal = function() {
            $scope.address_modal.hide();
        }

        $scope.$on("$destroy", function() {
            $scope.address_modal.remove();
        });


        $scope.register = function(){
            if(checkInput()){
                $ionicLoading.show();
                var id_begindate = new XDate(par.id_begindate).toString('yyyyMMdd');
                var id_enddate;
                if( par.isLongTerm) {
                    id_enddate = DictionaryService.getDefEndtime();
                } else {
                    id_enddate = new XDate(par.id_enddate).toString('yyyyMMdd');
                }
                var params = {client_name: par.client_name,id_no: par.id_no,profession_code: par.profession_code,degree_code: par.degree_code,
                    issued_depart : par.issued_depart,id_begindate : id_begindate, id_enddate : id_enddate,
                    conduit_no: LocalCacheService.getRecommendInfos(),
                    recommend_no: par.recommend_no,branch_no: par.branch_no,id_address:par.id_address,source: CommonService.getSource()};
                WebService.open(params).then(
                    function(data){
                        $ionicLoading.hide();
                        $state.go('open-installCert');
                    },
                    function(result){
                        if("XCM-100006,XCM-100007".indexOf(result.error_no) > -1){
                            var myPopup = $ionicPopup.show({
                                cssClass: "kDialog",
                                template: "无法获取客户公安信息。请核实身份证号和姓名后重试。如有疑问，请联系客服：400-800-5000。",
                                scope: $scope,
                                buttons: [
                                    { text: "重新上传",
                                        onTap: function(e) {
                                            $scope.goUploadId();
                                            return false;
                                        }
                                    }
                                ]
                            });
                        } else {
                            CommonService.showAlert({message:result.error_info});
                        }

                    }
                );
            }
        };

        function checkInput(){
            if(CommonService.isStrEmpty(par.client_name)){
                CommonService.showAlert({message:"请输入姓名！"});
                return false;
            }
            if(CommonService.isStrEmpty(par.id_no)){
                CommonService.showAlert({message:"请输入身份证号！"});
                return false;
            }
            if(CommonService.isStrEmpty(par.id_address)){
                CommonService.showAlert({message:"请输入身份证地址！"});
                return false;
            }
            if(CommonService.isStrEmpty(par.id_begindate) || isNaN(par.id_begindate.getTime())){
                CommonService.showAlert({message:"请选择身份证有效期起始日期！"});
                return false;
            }
            if(par.id_begindate > new Date()){
                CommonService.showAlert({message:"身份证有效期起始日期不可大于当前日期！"});
                return false;
            }
            if(!par.isLongTerm) {
                if(CommonService.isStrEmpty(par.id_enddate) || isNaN(par.id_enddate.getTime())){
                    CommonService.showAlert({message:"请选择身份证有效期截止日期！"});
                    return false;
                }
                if(par.id_enddate < new Date()){
                    CommonService.showAlert({message:"身份证有效期截止日期不可早于起始日期！"});
                    return false;
                }
            }
            if(CommonService.isStrEmpty(par.issued_depart)){
                CommonService.showAlert({message:"请输入签发机关！"});
                return false;
            }
            if(CommonService.isStrEmpty(par.profession_code)){
                CommonService.showAlert({message:"请选择职业！"});
                return false;
            }
            if(CommonService.isStrEmpty(par.degree_code)){
                CommonService.showAlert({message:"请选择学历！"});
                return false;
            }
            var birthday = CommonService.checkIdCard(par.id_no);
            if(!birthday){
                CommonService.showAlert({message:"身份证号码输入有误！"});
                return false;
            }
            var age = CommonService.jsGetAge(birthday);
            if(age < 18 || age > 70) {
                CommonService.showAlert({message:"您的年龄不符合开户要求，18岁--70岁之间可正常开户。"});
                return false;
            }
            return true;
        }
    }

    ctrl.$inject = ['$scope','$state','$ionicLoading','$ionicModal','$q','$ionicPopup','CommonService','DictionaryService','WebService','LocalCacheService'];
    return ctrl;
});